using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace MyWords
{
    public partial class WordBrower : UserControl
    {
        DateTime theDay = DateTime.Today;
        Word theWord = new Word();

        public WordBrower()
        {
            InitializeComponent();
        }

        private void WordViewer_Load(object sender, EventArgs e)
        {
            if (!this.DesignMode)
            {
                this.comboBoxOptions.SelectedIndex = 0;
            }
        }

        private void comboBoxOptions_SelectedIndexChanged(object sender, EventArgs e)
        {
            bool status = this.Active;
            this.Active = false;

            List<DateTime> DateList = new List<DateTime>();

            switch ((string)this.comboBoxOptions.SelectedItem)
            {
                case "Review":
                    DateList = DB.LoadAvailableScheduledDateList();
                    BindDateList(DateList);
                    break;

                case "Day":
                    DateList = DB.LoadAvailableAddedDateList();
                    BindDateList(DateList);
                    break;

                case "All":
                    this.listBoxDate.Items.Clear();
                    this.LoadWords4theDay();
                    break;
            }

            this.Active = status;
        }

        private void BindDateList(List<DateTime> DateList)
        {
            DateTime Today = DateTime.Today;
            int indexOfToday = -1;
            TimeSpan x = new TimeSpan(1000, 0, 0, 0);
            this.listBoxDate.Items.Clear();
            for (int i = 0; i<DateList.Count; i++)
            {
                DateTime dt = DateList[i];
                this.listBoxDate.Items.Add(dt);
                TimeSpan x1 = dt > Today ? dt - Today : Today - dt;
                if (x1 <= x)
                {
                    indexOfToday = i;
                    x = x1;
                }
            }
            this.listBoxDate.SelectedIndex = indexOfToday;
        }

        private void listBoxDate_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.listBoxDate.SelectedIndex >= 0)
            {
                this.theDay = (DateTime)this.listBoxDate.SelectedItem;
                this.LoadWords4theDay();
            }
        }


        private void LoadWords4theDay()
        {
            //this.isLoading = true;


            WordList wordList1 = DB.LoadWords(this.theDay, this.theDay.AddDays(1));
            switch ((string)this.comboBoxOptions.SelectedItem)
            {
                case "Review":
                    wordList1 = DB.LoadScheduledWords(this.theDay);
                    break;
                case "Day":
                    wordList1 = DB.LoadWords(this.theDay, this.theDay.AddDays(1));
                    break;
                case "All":
                    wordList1 = DB.LoadWords(DateTime.Parse("2000-01-01"), DateTime.Parse("2100-01-01"));
                    wordList1.SortByHead();
                    break;
            }

            this.listBox1.Items.Clear();

            foreach (Word aWord in wordList1)
            {
                this.listBox1.Items.Add(aWord);
            }

            if (this.listBox1.Items.Count > 0)
                this.listBox1.SelectedIndex = 0;

            //this.isLoading = false;

            //this.listBox1_SelectedIndexChanged(null, null);
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //if (this.isLoading) return;

            this.timer1.Stop();
            if (this.checkBoxAutoPlay.Checked) this.timer1.Start();

            if (this.listBox1.SelectedIndex >= 0)
            {
                if (this.theWord!=null && this.theWord.Head != "")
                {
                    this.theWord.UpdateStudyInfo(DateTime.Now);
                    DB.SaveWord(this.theWord);
                }

                this.theWord = (Word)this.listBox1.SelectedItem;
                Utility.PlayAudio(this.theWord);
            }
            else
            {
                this.theWord = new Word();
            }
            this.BindWord(this.theWord);
        }
        
        private void BindWord(Word aWord)
        {
            if (this.checkBoxClipboard.Checked && aWord.Head!=null && aWord.Head!="") Clipboard.SetText(aWord.Head); 
            this.headTextBox.Text = aWord.Head;
            this.meaningTextBox.Text = aWord.Meaning;

            if (aWord.Head == "")
                this.buttonSave.Enabled = false;
            else
                this.buttonSave.Enabled = true;

            this.labelSchedule.Text = "";
            this.labelStudy.Text = "";

            foreach (Schedule aSchedule in aWord.Schedules)
            {
                if (aSchedule.StudyDate.IsNull)
                {
                    this.labelSchedule.Text += ((TimeSpan)(aSchedule.ScheduleDate.Value.Date - DateTime.Today)).TotalDays.ToString() + ",  ";
                }
                else
                {
                    this.labelStudy.Text += ((TimeSpan)(DateTime.Today - aSchedule.StudyDate.Value.Date)).TotalDays.ToString() + ",  ";
                }
            }
        }

        private void buttonSave_Click(object sender, EventArgs e)
        {
            string oldHead = this.theWord.Head;

            meaningTextBox.Text = meaningTextBox.Text.Trim();
            headTextBox.Text = headTextBox.Text.Trim();

            this.theWord.Head = this.headTextBox.Text;
            this.theWord.Meaning = this.meaningTextBox.Text;

            DB.UpdateWordHeadMeaning(this.theWord, oldHead);
            DB.SaveAudio(this.theWord);

            int index = this.listBox1.SelectedIndex;
            if (index >= 0)
            {
                Word aWord = (Word)this.listBox1.SelectedItem;
                if (aWord.Head == oldHead)
                {
                    aWord.Head = this.theWord.Head;
                    aWord.Meaning = this.theWord.Meaning;
                    this.listBox1.Refresh();
                }

            }
        }

        private void buttonRec_Click(object sender, EventArgs e)
        {
            if (this.theWord.Head.Length == 0) return;
            if (this.buttonRec.Text != "Stop")
            {
                this.buttonRec.BackColor = Color.Red;
                this.buttonRec.Text = "Stop";
                MyAudio.AudioRecorder.Rewind();
                MyAudio.AudioRecorder.StartRecord();
            }
            else
            {
                this.buttonRec.BackColor = Color.Gold;
                this.buttonRec.Text = "Rec Audio";
                MyAudio.AudioRecorder.StopRecord();
                byte[] audioBytes = MyAudio.AudioRecorder.SaveToBytes();

                this.theWord.Audio = AudioFormat.Original;
                this.theWord.AudioBytes = audioBytes;
            }
        }

        private void buttonStopPlay_Click(object sender, EventArgs e)
        {
            Utility.StopAudio();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (this.listBox1.Items.Count > 1)
            {
                int i = this.listBox1.SelectedIndex+1;
                i = i % this.listBox1.Items.Count;
                this.listBox1.SelectedIndex = i;
            }
        }

        public void Play()
        {
            this.checkBoxAutoPlay.Checked = true;
            Utility.PlayAudio(this.theWord);
        }
        public void Pause()
        {
            this.checkBoxAutoPlay.Checked = !this.checkBoxAutoPlay.Checked;
            if (this.checkBoxAutoPlay.Checked)
            {
                this.checkBoxAutoPlay.Checked = false;
                Utility.StopAudio();
            }
            else
            {
                this.Play();
            }
        }

        private void numericUpDown1_ValueChanged(object sender, EventArgs e)
        {
            this.timer1.Stop();
            this.timer1.Interval = Convert.ToInt32(this.numericUpDown1.Value) * 1000;
            if (this.checkBoxAutoPlay.Checked) this.timer1.Start();
        }

        private bool m_Active = false;
        public bool Active
        {
            get
            {
                return m_Active;
            }
            set
            {
                m_Active = value;
                if (!m_Active)
                {
                    this.timer1.Stop();
                    Utility.StopAudio();
                }
                else
                {
                    Utility.PlayAudio(theWord);
                    if (this.checkBoxAutoPlay.Checked) this.timer1.Start();
                }
            }
        }

        private void checkBoxAutoPlay_CheckedChanged(object sender, EventArgs e)
        {
            if (this.checkBoxAutoPlay.Checked)
            {
                this.timer1.Start();
            }
            else
            {
                this.timer1.Stop();
            }
        }

        private void listBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                if (this.listBox1.SelectedIndex >= 0)
                {
                    bool status = this.Active;
                    this.Active = false;

                    Word aWord = (Word)this.listBox1.SelectedItem;
                    DB.DeleteWord(aWord.Head);

                    int cur = this.listBox1.SelectedIndex;
                    this.listBox1.Items.RemoveAt(cur);
                    if (this.listBox1.Items.Count > 0)
                    {
                        this.listBox1.SelectedIndex = cur % this.listBox1.Items.Count;
                    }

                    this.Active = status;
                }
            }
        }

    }
}
